using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Office.Server.Search.Query;
using Microsoft.SharePoint;
using System.Web;
using System.Web.Configuration;
using System.Diagnostics;

namespace CKS.EBE.Search
{
    public class SearchSqlQueryResults : SearchKeywordResults
    {
        private string _orderByText = "ORDER BY Rank Desc";
        protected bool _customOrderBy = false;
        private string _additionalColumns = "";
        private string _additionalWhere = "";

        public string AdditionalWhere
        {
            get { return _additionalWhere; }
            set { _additionalWhere = value; }
        }

        public string AdditionalColumns
        {
            get { return ((!string.IsNullOrEmpty(_additionalColumns)) ? ", " : "") + _additionalColumns; }
            set { _additionalColumns = value; }
        }

        public string OrderByText
        {
            get
            {
                if (string.IsNullOrEmpty(_orderByText)) return "";

                if (!_customOrderBy)
                {
                    string sOrder = Page.Request.QueryString["DateOrder"];
                    if (!string.IsNullOrEmpty(sOrder) && sOrder.ToLower() == "true")
                        return "ORDER By Write Desc";
                }

                return _orderByText;

            }
            set { _orderByText = value; _customOrderBy = true; }
        }

        private string _queryText = "SELECT Rank, Title, Url, ContentClass, IsDocument, ContentSource, FileExtension, HitHighlightedSummary, WorkId, Write, Author{4} FROM Scope() WHERE FREETEXT(defaultproperties, '{0}') {5} {3}";
        public string QueryText
        {
            get { return _queryText; }
            set { _queryText = value; }
        }

        protected override Microsoft.Office.Server.Search.Query.Query GetQuery()
        {
            string q = HttpContext.Current.Request[QueryParameter];

            FullTextSqlQuery fq = new FullTextSqlQuery(SPContext.Current.Site);

            fq.QueryText = string.Format(QueryText, q, SPContext.Current.Web.Url, SPContext.Current.Site.Url, OrderByText, AdditionalColumns, AdditionalWhere);

            Debug.WriteLine(fq.QueryText);

            return fq;
        }
    }
}
